package com.chen.librarysystem.menu;

import com.chen.librarysystem.context.AppContext;
import com.chen.librarysystem.entry.User;
import com.chen.librarysystem.log.LibraryLog;
import com.chen.librarysystem.service.UserService;
import com.chen.librarysystem.service.impl.UserServiceImpl;
import com.chen.librarysystem.util.PrintUtils;

import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;

public class UserManagementMenu implements Menu {
    private static final UserService userService = new UserServiceImpl();
    public static final Scanner sc = AppContext.getInstance().getScanner();

    @Override
    public void start() {
        while (true) {
            System.out.println("=========欢迎来到用户管理界面==========");
            System.out.println("1. 查看用户");
            System.out.println("2. 修改密码");
            System.out.println("3. 退出用户管理界面");
            int type = PrintUtils.getIntInput(sc, "请输入您的选择:");
            switch (type) {
                case 1:
                    LibraryLog.log(Level.INFO, "查看用户");
                    getUserByName();
                    break;
                case 2:
                    LibraryLog.log(Level.INFO, "修改密码");
                    changePassword();
                    break;
                case 3:
                    LibraryLog.log(Level.INFO, "退出用户管理界面");
                    return;
                default:
                    System.out.println("输入错误，请重新输入！");
            }
        }
    }

    private void changePassword() {
        String oldPassword = PrintUtils.getInput("请输入旧密码:");
        String newPassword = PrintUtils.getInput("请输入新密码:");
        userService.changePassword(AppContext.getInstance().getUserName(), oldPassword, newPassword);
        System.out.println("修改密码成功！");
        LibraryLog.log(Level.INFO, "用户:" + AppContext.getInstance().getUserName() + "修改了密码！");
    }

    private void getUserByName() {
        User user = userService.getUserByName(AppContext.getInstance().getUserName());
        if (user == null) {
            System.out.println("用户不存在！");
            return;
        }
        PrintUtils.printUsers(List.of(user));
        LibraryLog.log(Level.INFO, "查询用户信息成功！");
    }
}
